<template>
    <div class="common-page page-flow-demand-add" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/flow', '/flow/demands/type4', $route.fullPath]"></comp-paths>
            <div class="title"></div>
        </div>
        <div class="common-page__body"></div>
        <comp-dialog title="提交需求" ref="demand" @close="addDemand('end')">
            <el-form size="small" label-width="112px" style="margin-right: 20px" @submit.native.prevent v-if="demand">
                <el-form-item label="企业/项目：" required>
                    <div style="margin-bottom: 10px; width: 360px" v-if="demand.company.id">
                        <el-tag disable-transitions>{{ demand.company.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-refresh" @click="addDemand('pick-company-start')" v-if="demand.company.id">更换企业/项目</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="addDemand('pick-company-start')" v-else>选择企业/项目</el-button>
                </el-form-item>
                <el-form-item label="需求类型：" required>
                    <el-select v-model="demand.type" style="width: 360px" placeholder="请选择" @change="addDemand('validate')">
                        <el-option v-for="data in env.demandTypes" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="需求标题：" required>
                    <el-input v-model="demand.title" style="width: 360px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="需求描述：" required>
                    <el-input type="textarea" v-model="demand.content" style="width: 360px" placeholder="请输入" :maxlength="1000" :rows="5" resize="none" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="联系人姓名：" required>
                    <el-input v-model="demand.contacts.name" style="width: 360px" placeholder="请输入" :maxlength="20" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="联系人电话：" required>
                    <el-input v-model="demand.contacts.mobile" style="width: 360px" placeholder="请输入" :maxlength="20" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="需求附件：">
                    <div style="width: 360px">
                        <el-tag style="margin: 0 10px 10px 0" v-for="(file, index) in demand.files" :key="index" disable-transitions closable @close="addDemand('demand-file-delete', file)">{{ file.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-plus" @click="addDemand('demand-file-upload', 'image')">选择图片</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="addDemand('demand-file-upload', 'document')">选择文档</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addDemand('submit')">提交</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addDemand('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="选择企业/项目" width="80vw" height="80vh" ref="companyPicker">
            <comp-companys style="height: 100%" ref="companyPickerList" :limit="limit" v-if="demand">
                <template #body="scope">
                    <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="addDemand('pick-company-submit', scope.data)">选择</el-button>
                </template>
                <template #foot="scope">
                    <el-button type="danger" size="small" icon="el-icon-close" @click="addDemand('pick-company-end')">放弃</el-button>
                </template>
            </comp-companys>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, selectFile } from "../util";
    export default {
        name: "page-flow-demand-add",
        title: "提交需求",
        nodes: ["/menu/flow"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            demand: null,
            limit: "",
        }),
        methods: {
            addDemand(action, data) {
                if (this.loading) return;
                let demand = this.demand;
                if (action === "start" || !action) {
                    this.demand = this.plugins.user.formatDemand();
                    this.addDemand("validate");
                    this.$refs.demand.init();
                } else if (action === "validate") {
                    let form = demand;
                    let error = "";
                    error = error || (form.company.id ? "" : "请先选择企业/项目！");
                    error = error || (form.type ? "" : "请先选择需求类型！");
                    form.title = string(form.title).trim();
                    error = error || (form.title ? "" : "请先输入需求标题！");
                    form.content = string(form.content);
                    error = error || (form.content ? "" : "请先输入需求描述！");
                    form.contacts.name = string(form.contacts.name).trim();
                    error = error || (form.contacts.name ? "" : "请先输入联系人姓名！");
                    form.contacts.mobile = string(form.contacts.mobile).trim();
                    error = error || (form.contacts.mobile ? "" : "请先输入联系人电话！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "pick-company-start") {
                    this.$refs.companyPicker.init();
                    this.$nextTick(() => this.$refs.companyPickerList.init());
                } else if (action === "pick-company-submit") {
                    if (data) demand.company.id = data.id;
                    if (data) demand.company.name = data.name;
                    this.addDemand("pick-company-end");
                } else if (action === "pick-company-end") {
                    this.addDemand("validate");
                    this.$refs.companyPicker.close();
                } else if (action === "demand-file-upload") {
                    let type = data;
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    let upload = (type, file) => {
                        this.loading = true;
                        this.plugins.user.uploadFile(file, type, progress).then((res) => {
                            this.loading = false;
                            if (res.code === 0) {
                                demand.files.push(res.data);
                                this.addDemand("validate");
                            } else {
                                this.plugins.modal.alert("上传失败", res.code + "：" + res.msg, "error");
                            }
                        });
                    };
                    if (type === "image") selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else upload(type, file);
                    });
                    if (type === "document") selectFile(".xls,.xlsx,.doc,.docx,.pdf").then((file) => {
                        if (file.size > 10 * 1048576) this.plugins.modal.toast("文档过大，不能大于10MB哦！请重新选择。", "error");
                        else upload(type, file);
                    });
                } else if (action === "demand-file-delete") {
                    let file = data;
                    let index = demand.files.indexOf(file);
                    if (index > -1) demand.files.splice(index, 1);
                } else if (action === "submit") {
                    if (!this.addDemand("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.addDemand(demand).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("提交成功！", "success");
                            this.addDemand("end");
                            this.$nextTick(() => this.$router.replace("/flow/demands/type1"));
                        } else {
                            this.plugins.modal.alert("提交失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.demand.close();
                    this.$router.back();
                }
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                this.loading = true;
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.limit = this.profile.role === "staff" ? "employee" : "dept";
                        this.addDemand();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/flow/demands/type4"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-flow-demand-add {
        overflow: hidden;
    }
</style>